// StiLib.cpp: implementation of the CStiLib class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "CrossStitch.h"
#include "StiFlossTable.h"
#include "ColFile.h"

#include "StiLib.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CStiLib::CStiLib(CString name, CString desc)
{
	m_pFlosses = new CStiFlossTable();
	m_LibName = name;
	m_Desc = "";
}

CStiLib::~CStiLib()
{
	if (m_pFlosses)
	{
// 		m_pFlosses->Clear();
		delete m_pFlosses;
		m_pFlosses = NULL;
	}
}

UINT CStiLib::GetColor( int id )
{
	return 0;
}

void CStiLib::SetColor( int id, UINT clr )
{
	
}

int CStiLib::ReadFromCol( CString fileName )
{
	return LoadColFile(this, fileName);
}

int CStiLib::WritetoCol( CString fileName )
{
	return WriteColFile(this, fileName);
}

void CStiLib::Serialize( CArchive& ar )
{
	
}

static char pBuf[1024*1024];
int CStiLib::Load( char* fileName )
{
	CFile file;
	if (!file.Open(fileName, CFile::shareDenyRead))
		return -1;

	int len = file.Read(pBuf, 1024*1024);
	if (len == 1024*1024)
	{
		// big than 1M
		return -1;
	}
	pBuf[len] = '\0';
	CString str = pBuf;
	int offset = 0;
	CString name, desc, rgb;
	int idx = 0;
	int ret = 0;
	do
	{
		ret = str.Find('\r', offset);
		if (str.GetAt(ret+1) == '\n')
		{
			ret ++;
		}
		switch (idx%3)
		{
		case 0:
			name = str.Mid(offset, ret-offset);
			break;
		case 1:
			desc = str.Mid(offset, ret-offset);
			break;
		default:
			{
				int a,b;
				CString value;
				COLORREF color;
				rgb = str.Mid(offset, ret-offset);
				a = rgb.Find(',');
				value = rgb.Mid(0, a);
				color = atoi(value.GetBuffer(0));
				b = rgb.Find(',', a+1);
				value = rgb.Mid(a+1, b-a-1);
				color |= atoi(value.GetBuffer(0))<<8;
				value = rgb.Mid(b+1, rgb.GetLength()-b-1);
				color |= atoi(value.GetBuffer(0))<<16;
				FLOSS* floss = new FLOSS;
				floss->color = color;
				this->m_pFlosses->AddFloss(floss);
			}
			break;
		}
		offset = ret;

		idx++;
	}while(ret!=-1);
	if (0==m_pFlosses->GetCount())
	{
		// not find any floss information, not valid stitch txt file.
		return -1;
	}
	return 0;
}

int CStiLib::MatchColor( COLORREF clr, COLORREF clr2 )
{
	int ret = 0;
	int R1 = (clr&0xFF0000)>>16;
	int R2 = (clr2&0xFF0000)>>16;
	int dR = R1>R2?R1-R2:R2-R1;

	int G1 = (clr&0xFF00)>>8;
	int G2 = (clr2&0xFF00)>>8;
	int dG = G1>G2?G1-G2:G2-G1;

	int B1 = clr&0xFF;
	int B2 = clr2&0xFF;
	int dB = B1>B2?B1-B2:B2-B1;

	ret = 255-(dR*RED_WEIGHT+dG*GREEN_WEIGHT+dB*BLUE_WEIGHT);
	return ret;
}
